package leetcode.editor.cn;

/**
 * 二分查找
 * 2023-11-13 20:31:03
 */
class BinarySearch {
    public static void main(String[] args) {
        Solution solution = new BinarySearch().new Solution();
        solution.binarySearch();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int search(int[] nums, int target) {
            //看题目可以看到这是一个左闭右闭的区间，所以我们在处理临界时就要注意对应的处理方法
            //解题思路：1.先排除目标值不在区间的情况  2.目标值在区间，一步步缩小区间
//            if (target < nums[0] || target > nums[nums.length - 1]) {
//                return -1;
//            }
//            int left = 0, right = nums.length - 1;
//            while (left <= right) {
//                int mid = left + ((right - left) >> 1);
//                if (nums[mid] == target)
//                    return mid;
//                else if (nums[mid] < target) {
//                    left = mid + 1;
//                } else if (nums[mid] > target) {
//                    right = mid - 1;
//                }
//            }
//            return -1;
//        }

            //左闭右开
            if (target >= nums[nums.length - 1] || target < nums[0]) {
                return -1
            }
            int left = 0, right = nums.length - 1;
            while (left < right) {
                int mid = left + ((right - left) >> 1)
                if (nums[mid] == target) {
                    return mid;
                } else if (target > nums[mid]) {
                    left = mid + 1;
                } else if (target < nums[mid]) {
                    right = mid
                }
            }
            return -1;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)
}